package com.ly.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.ly.bean.Result;
import com.ly.service.MailService;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.mail.internet.MimeMessage;

/**
 * @author 李岩
 * @date 2021/12/24-11:30
 * @describe
 */
@Component
@Service(interfaceClass = MailService.class)
public class MailServiceImpl implements MailService {
    private final Logger logger= LoggerFactory.getLogger(MailServiceImpl.class);
    private MailServiceImpl(){
        System.out.println("MailServiceImpl   的service层");
    }
    @Autowired
    private JavaMailSender mailSender;
    private String from ="1273067337@qq.com";
    @Override
    public Result sendTextMail(String to, String subject, String content) {
        logger.info("给"+to+"发送邮件："+content);
        try {
            SimpleMailMessage message = new SimpleMailMessage();
            message.setFrom(from);
            message.setTo(to);
            message.setSubject(subject);
            message.setText(content);
            mailSender.send(message);
            logger.info("简单邮件已经发送。");
            return Result.getResult(true,200,"简单邮件发送成功",null);
        } catch (Exception e) {
            logger.error("发送简单邮件时发生异常！", e);
        }
        return Result.getResult(false,444,"简单邮件发送失败",null);

    }

    @Override
    public Result sendHtmlMail(String to, String subject, String content) {
        logger.info("给"+to+"发送邮件："+content);
        MimeMessage message = mailSender.createMimeMessage();
        try {
            //true表示需要创建一个multipart message
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content, true);

            //启动一个线程实现邮件的发送DirectConsumerOneListener
            new Thread(){
                @Override
                public void run() {
                    mailSender.send(message);
                }
            }.start();
            logger.info("html邮件发送成功");
        } catch (Exception e) {
            logger.error("发送html邮件时发生异常！", e);
            return Result.getResult(false,444,"html邮件发送失败",null);
        }
        return Result.getResult(true,200,"html邮件发送成功",null);
    }
}
